import { inject, observer } from "mobx-react";
import React from "react";
import { Image, Keyboard, ScrollView, StyleSheet, TextInput } from "react-native";
import SplashScreen from "react-native-splash-screen";
import { Button, Text, TouchableOpacity, View } from "react-native-ui-lib";
import { commonStyles } from "../configs/commonStyle";
import api from "../net/api";
import { IconImage } from "../utils";
import navigator from "../utils/navigator";
import { checkLocationPermission, logger } from "../utils/util";
import BasePage from "./BasePage";
import { isIOS, windowWidth } from "../configs/platform";
import { Icon } from "./components";
import ToastUtils from "../utils/ToastUtils";
import { getStatusBarHeight } from "react-native-iphone-x-helper";
import PermissionDialog from "./common/PermissionDialog";
import { start } from "react-native-amap-geolocation";
/**
 * 登录
 */
@inject("userStore", "appStore", "upgradeStore")
@observer
export default class Login extends BasePage {
  state = {
    // mobile: GLOBAL.__DEV__ ? "测试配送员三" : "",
    mobile: GLOBAL.__DEV__ ? "codewait" : "",
    // mobile: "录音测试一",
    // mobile: GLOBAL.__DEV__ ? "录音测试三" : "",
    // mobile: GLOBAL.__DEV__ ? "刘兴旺" : "",
    // mobile: GLOBAL.__DEV__ ? "黎敬科" : "",
    // mobile: GLOBAL.__DEV__ ? "袁晓飞" : "",
    // mobile: GLOBAL.__DEV__ ? "刘坤" : "",
    // mobile: GLOBAL.__DEV__ ? "卢俊伟" : "",
    // password: GLOBAL.__DEV__ ? "123456" : "",
    password: GLOBAL.__DEV__ ? "Xm@12345" : "",
    // password: GLOBAL.__DEV__ ? "lk123456" : "",
    smsCode: "",
    imgCode: "",
    timestamp: +new Date(),
    agree: true,
    needImgCode: false,
    isCiphertext: true,
    selectIndex: 1,
  };

  componentDidMount() {
    super.componentDidMount();
    SplashScreen.hide();
    this.getLocation();
    this.addLocationListener();
    this.props.upgradeStore.versionCheck();
    this.loadCacheLoginForm()
  }
  getLocation = async () => {
    let permissionResult = await checkLocationPermission();
    if (permissionResult == true) {
      start();
    } else {
      this.permissionDialog.show("需要根据您的位置配送,签收，请开启位置权限");
    }
  };

  onLogin = () => {
    Keyboard.dismiss();
    const { password, mobile, agree } = this.state;
    if (IsNullOrEmpty(mobile)) {
      ToastUtils.showFailInfo("请输入用户名");
      return;
    }
    if (IsNullOrEmpty(password)) {
      ToastUtils.showFailInfo("请输入密码");
      return;
    }
    if (IsNullOrEmpty(agree)) {
      ToastUtils.showFailInfo("请仔细阅读并同意服务协议及隐私政策");
      return;
    }
    axios.get(api.login, {
      params:{
        userName: mobile,
        pwd: password,
        showLoading: true,
      }
    })
      .then(res => {
        this.props.userStore.setValue("session", res.result);
        this.cacheLoginForm()
        navigator.resetToPage("MainPage");
      }).catch(e => {
      logger("e:", e);
      e.msg && ToastUtils.showFailInfo(e.msg);
    });
  };

  cacheLoginForm = () => {
    const { mobile, password } = this.state
    storage.save({
      key: 'loginForm',
      data: {
        mobile,
        password,
      }
    })
  }

  loadCacheLoginForm = async () => {
    const loginForm = await storage.load({
      key: 'loginForm'
    }).catch(logger)
    if (loginForm) {
      this.setState({
        mobile: loginForm.mobile,
        password: loginForm.password,
      })
    }
  }


  renderPwdPage = () => {
    const { agree, isCiphertext } = this.state;
    return (
      <ScrollView keyboardShouldPersistTaps={"always"}>
        <View marginH-20>
          <View row centerV>
            <Text style={commonStyles.text_black_14}>用户名</Text>
            <View style={{ ...styles.inputView }}>
              <TextInput placeholderTextColor="#959595"
                         style={{ ...styles.inputStyle }}
                         placeholder="请输入您的用户名"
                         autoCapitalize="none"
                         defaultValue={this.state.mobile}
                         onChangeText={value => this.setState({ mobile: value })} />
              {
                this.state.mobile ?
                  <TouchableOpacity activeOpacity={1} paddingL-10 onPress={() => {
                    this.setState({
                      mobile: "",
                    });
                  }}>
                    <Icon type="AntDesign" name={"closecircle"} size={19} color={"#BCBCBC"} />
                  </TouchableOpacity> : null
              }
            </View>
          </View>
          <View row centerV marginT-10>
            <Text style={commonStyles.text_black_14}>{`密    码`}</Text>
            <View style={{ ...styles.inputView }}>
              <TextInput placeholderTextColor="#959595"
                         style={{ ...styles.inputStyle }}
                         placeholder="输入密码"
                         secureTextEntry={isCiphertext}
                         defaultValue={this.state.password}
                         onChangeText={value => this.setState({ password: value })} />

              <TouchableOpacity paddingV-10 paddingL-10
                                onPress={() => this.setState({ isCiphertext: !isCiphertext })}>
                <Image source={isCiphertext ? IconImage.ic_ciphertext : IconImage.ic_plaintext}
                       style={{ height: 16, width: 22 }} /></TouchableOpacity>

            </View>
          </View>
          <View style={styles.protocol}>
            <TouchableOpacity onPress={() => this.setState({ agree: !agree })}>
              <Image style={{ height: 16, width: 16 }}
                     source={agree ? IconImage.ic_checked : IconImage.ic_unchecked} />
            </TouchableOpacity>
            <Text style={{ paddingLeft: 12, ...commonStyles.text_black }}>我已阅读并同意</Text>
            <View row centerV>
              <Text style={{ ...commonStyles.text_primary_14 }}>《</Text>
              <TouchableOpacity throttleTime={1000} activeOpacity={1} onPress={() => navigator.navigate("Protocol")}>
                <Text style={{ ...commonStyles.text_primary_14 }}>服务协议</Text>
              </TouchableOpacity>
              <Text style={{ ...commonStyles.text_primary_14 }}>和</Text>
              <TouchableOpacity throttleTime={1000} activeOpacity={1} onPress={() => navigator.navigate("Privacy")}>
                <Text style={{ ...commonStyles.text_primary_14 }}>隐私政策</Text>
              </TouchableOpacity>
              <Text style={{ ...commonStyles.text_primary_14 }}>》</Text>
            </View>
          </View>
        </View>
      </ScrollView>
    );
  };


  render() {
    return (
      <View style={commonStyles.body}>
        <View style={styles.bg_login}>
          <Image source={IconImage.logo} style={{ width: 300, height: 65 }} />
        </View>
        <View style={commonStyles.container}>
          <View style={styles.LoginForm}>
            {this.renderPwdPage()}
          </View>
          <Button label={"登录"}
                  marginH-15
                  style={{ borderRadius: 4 }}
                  bg-primary labelStyle={commonStyles.text_black}
                  onPress={this.onLogin} />
        </View>
        <PermissionDialog ref={r => this.permissionDialog = r} />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  bg_login: {
    width: "100%",
    height: 180 + (isIOS() ? getStatusBarHeight(true) : 0),
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#F9D63B",
  },
  LoginForm: {
    marginTop: -20,
    backgroundColor: "white",
    borderRadius: 10,
    marginHorizontal: 15,
    paddingVertical: 20,
    marginBottom: 20,
  },
  inputView: {
    backgroundColor: "#F7F7F7",
    flex: 1,
    borderRadius: 4,
    paddingHorizontal: 10,
    flexDirection: "row",
    alignItems: "center",
    height: 35,
    marginLeft: 10,
  },
  bg_line: {
    backgroundColor: "#FED13F",
    width: 80,
    height: 12,
    position: "absolute",
    bottom: 0,
    right: -4,
    zIndex: -10,
  },
  btn_login: {
    width: (windowWidth - 70),
    height: (windowWidth - 70) * 94 / 622,
    alignSelf: "center",
    ...commonStyles.center,
  },
  appIcon: {
    width: 109,
    height: 109,
    position: "absolute",
    bottom: -40,
  },

  iconSmall: {
    width: 24,
    height: 24,
    marginRight: 14,
  },

  inputStyle: {
    color: "#333333",
    fontSize: 14,
    flex: 1,
    padding: 0,
    height: 35,
  },

  line: {
    backgroundColor: "#FF006C",
    width: 3,
    borderRadius: 2,
    height: 15,
    marginRight: 5,
  },
  countButton: {
    width: 86,
    height: 29,
    backgroundColor: "#427FFE",
    borderRadius: 16,
  },
  protocol: { marginTop: 20, flexDirection: "row", alignItems: "center", justifyContent: "center" },

});

